//
//  HomeTableViewController.swift
//  LVWeibo
//
//  Created by lv on 15/6/23.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 行高缓存
 var rowHeightCache = [Int: CGFloat]()
class HomeTableViewController: BaseTableViewController,StatusCellDelegate {
    // 上拉刷新标识
    private var pullRefreshFlag = false
    
    // 表格绑定的微博数据
    var statusLists : [Status]? {
        didSet {
            // 刷新表格数据
            tableView.reloadData()
        }
    }
    
    // 标题按钮
    var homeTitleBtn = HomeTitleButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        visitorView?.setUpViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        // 设置导航栏按钮
        setupNavigationBar()
        
        // 加载微博数据前作用户登录判断
        if sharedUserAccount == nil {
            return
        }
        // 设置tableView
        prepareForTableView()
        // 设置下拉刷新控件
        prepareRefreshControl()
    }
    
    //MARK:- 刷新控件加载数据
    private func prepareRefreshControl() {
        
        refreshControl = WBRefreshControl()
        refreshControl!.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        // 加载微博数据
        loadData()
    }
    
    //MARK:- tableView
    private func prepareForTableView() {
        // 注册可重用cell
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: WBStatusForwardCellIdentifier)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: WBStatusNormalCellIdentifier)
        // 取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        // 取消滚动条
        tableView.showsVerticalScrollIndicator = false
    }
    
    // MARK:- 加载微博数据
    func loadData() {
        // 开始刷新 beginRefreshing() 只会开启刷新控件的动作，但是不会主动触发监听方法
        refreshControl?.beginRefreshing()
        
        // 下拉刷新代号，取数组中的第一条数据的id
        print("since_id：\(statusLists?.first?.id)")
        var since_id = statusLists?.first?.id ?? 0
        // 上拉刷新代号，取数组中的最后一条数据的id
        var max_id = 0
        if pullRefreshFlag {
            since_id = 0
            max_id = statusLists?.last?.id ?? 0
        }
        
        Status.loadStatuses(since_id,max_id: max_id) {(result, error) -> () in
            // 关闭刷新控件
            self.refreshControl?.endRefreshing()
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络好像不给力")
                // 关闭刷新控件
                self.refreshControl?.endRefreshing()
                return
            }
            if result == nil {
                print("没有数据")
                // 关闭刷新控件
                self.refreshControl?.endRefreshing()
                return
            }
            // 新加载微博数
            print("加载了\(result?.count)条微博")
            print(since_id)
            // 判断是否下拉刷新
            if since_id > 0 {
                self.statusLists = result! + self.statusLists!
            }else if max_id > 0{
                self.statusLists = self.statusLists! + result!
                self.pullRefreshFlag = false
            }else{
                // 初始刷新
                self.statusLists = result
            }
        }
    }
    
    // MARK:- 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusLists?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        // 1.获取模型数据
        let status = statusLists![indexPath.row]
        
        // 2. 获取cell的可重用ID
        let ID = StatusCell.cellIdentifier(status)
        
        // 3. 创建cell
        // 此方法必须注册可重用cell，否则会崩溃
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! StatusCell
        
        // 设置cell的代理
        cell.photoDelegate = self
        
        // 4. 设置数据
        cell.status = status
        
        // 5.判断是否为最后一行
        if indexPath.row == statusLists!.count - 1{
            pullRefreshFlag = true
            loadData()
        }
        return cell
    }
    
    // 行高代理方法
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        // 1.获取微博模型数据
        let status = statusLists![indexPath.row]
        
        // 2.判断行高是否缓存
        if rowHeightCache[status.id] != nil {
            return rowHeightCache[status.id]!
        }
        // 3.获取 cell － 计算行高准确，需要实例化一个cell
        // 3.1 获取cell的可重用ID
        let ID = StatusCell.cellIdentifier(status)
        // 3.2 定义一个类，默认是原创微博的cell
        var cellClass:AnyClass = StatusNormalCell.self
        if ID == WBStatusForwardCellIdentifier {
            cellClass = StatusForwardCell.self
        }
        // 3.3 创建cell
        let cell = cellClass.new() as! StatusCell
        
        let height = cell.rowHeight(statusLists![indexPath.row])
        rowHeightCache[status.id] = height
        return height
    }
    
    //MARK:- 实现cell的代理方法
    func statusCellDidSelectedPhoto(cell: StatusCell, photoIndex: Int) {
        
        if cell.status?.middlePicURLs == nil {
            return
        }
        // 初始化图片浏览控制器
        let vc = PhotoBrowserViewController(urls: cell.status!.middlePicURLs!, photoIndex: photoIndex)
        // 设置转场动画代理和样式
        vc.transitioningDelegate = self
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc, animated: true , completion: nil)
    }
    
    //MARK:- 内存警告
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        // 清空缓存，提示：NSCache 不能清空
        rowHeightCache.removeAll()
    }
    
    //==================显示扫描二维码界面==================
    func scanQRCode() {
        
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(sb.instantiateInitialViewController()!, animated: true, completion: nil)
    }
    
    //==================设置首页MODAL动画==================
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 开始动画
        visitorView?.startAnimation()
    }
    
    //MARK:- 设置导航栏按钮
    private func setupNavigationBar() {
        // 判断用户是否登陆
        if sharedUserAccount == nil {
            return
        }
        // 登陆
        // 1.设置导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightedImageName: nil)
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", highlightedImageName: nil)
        
        // 1.1 获取按钮
        let btn = navigationItem.rightBarButtonItem?.customView as! UIButton
        // 1.2 设置按钮点击事件
        btn.addTarget(self, action: "scanQRCode", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 2.设置标题按钮
        let title = sharedUserAccount!.name!
        let titleBtn = HomeTitleButton.button(title)
        // 按钮监听方法
        titleBtn.addTarget(self, action: "titleBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        homeTitleBtn = titleBtn
        navigationItem.titleView = titleBtn
    }
    
    // 动画转场代理
    let popoverAnimator = PopoverAnimator()
    
    //MARK:- titleBtn点击事件
    func titleBtnClick() {

        // 0.按钮图片朝上
        homeTitleBtn.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Normal)
        // 1.加载FriendGroup
        let FriendGroupSB = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = FriendGroupSB.instantiateViewControllerWithIdentifier("FriendGroupSB")
        
        // 2.设置转场transitioning 代理
        vc.transitioningDelegate = popoverAnimator
        
        // 3.设置转场的模式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        // 4.设置转场视图显示的大小
        let x = (view.bounds.width - 160) * 0.5
        popoverAnimator.presentFrame = CGRectMake(x, 56, 160, 240)
        presentViewController(vc, animated: true, completion: nil)
    }
}

// 是否展现标记
private var isPresented = false

//MARK:- 转场动画代理
extension HomeTableViewController: UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning {
    
    // 返回提供转场Modal动画的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    // 解除转场
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
    
    ///  实现UIViewControllerAnimatedTransitioning的协议方法
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    // 一旦实现，需要程序员提供动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        // 获取目标视图
        let viewKey = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let targetView = transitionContext.viewForKey(viewKey)
        
        if targetView == nil {
            return
        }
        if isPresented {
            // 添加toView
            transitionContext.containerView()?.addSubview(targetView!)
            targetView!.alpha = 0
            
            // 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                    targetView!.alpha = 1
                }, completion: { (_) -> Void in
                    // 告诉系统动画完成
                    transitionContext.completeTransition(true)
            })
        }else {
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                targetView!.alpha = 0
                }, completion: { (_) -> Void in
                    // 告诉系统动画完成
                    transitionContext.completeTransition(true)
            })
            
        }
    }

 }
